<template>
  <div class="container">
    <div style="text-align:left;margin-bottom:10px">
      <a-button type="primary" @click="onAddFruit">新增</a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="false"
      row-key="id"
    >
      <template slot="action" slot-scope="text, record">
        <a-button type="link" @click="onModifyFruit(record)">修改</a-button>&nbsp;&nbsp;
        <a-button type="link" @click="onDeleteFruit(record)">删除</a-button>
      </template>
    </a-table>

    <FruitForm ref="AddFruit" type="add" :data="data" @addSuccess="onAddSuccess" />
    <FruitForm ref="ModifyFruit" type="modify" :curr-record="currRecord" @modifySuccess="onModifySuccess" />
  </div>
</template>

<script>
import Vue from 'vue'
import {
  Button,
  Table,
  Modal
} from 'ant-design-vue'
import { columns } from './dict.js'
import FruitForm from './modals/FruitForm.vue'

Vue.use(Button)
Vue.use(Table)
Vue.use(Modal)

export default {
  components: {
    FruitForm
  },

  data () {
    return {
      columns,
      data: [
        {
          id: 1,
          name: '苹果',
          unitPrice: 2,
          inventory: 100
        }
      ],
      currRecord: {}
    }
  },

  methods: {
    onAddFruit () {
      this.$refs.AddFruit.visible = true
    },

    onModifyFruit (record) {
      this.currRecord = record
      this.$refs.ModifyFruit.visible = true
    },

    onAddSuccess (item) {
      this.data.push(item)
    },

    onModifySuccess (item) {
      const index = this.data.findIndex(ele => ele.id === item.id)
      this.$set(this.data, index, item)
    },

    onDeleteFruit (record) {
      Modal.confirm({
        title: '提示',
        content: '你确定要删除这个水果吗？',
        okType: 'danger',
        onOk: () => {
          const index = this.data.findIndex(ele => ele.id === record.id)
          this.data.splice(index, 1)
          this.$message.success('删除成功')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  background-color: white;
  overflow-y: auto;
}

.container::-webkit-scrollbar{
  width: 4px;
  height: 4px;
}

.container::-webkit-scrollbar-track{
  border-radius: 10px;
  background-color: #efefef;
}

.container::-webkit-scrollbar-thumb{
  border-radius: 10px;
  background-color: #ccc;
}
</style>
